using System;
using System.Windows.Forms;
using System.Text;
using FBroSharp.Lib;
using FBroSharp.Event;
using FBroSharp.DataType;
using FBroSharp.Value;
using FBroSharp.Const;

namespace WebSocket监控器
{
    /// <summary>
    /// 浏览器事件处理器 - MANDATORY for browser creation
    /// </summary>
    public class BrowserEvent : FBroSharpBrowserEvent
    {
        private Form1 _form;

        public BrowserEvent(Form1 form)
        {
            _form = form;
        }

        /// <summary>
        /// ⚠️ REQUIRED: Browser created (TWO parameters!)
        /// </summary>
        public override void OnAfterCreated(IFBroSharpBrowser browser, IFBroSharpDictionaryValue extrainfo)
        {
            Console.WriteLine($"[BrowserEvent] 浏览器创建完成，ID：{browser.GetIdentifier()}");
            
            if (!extrainfo.GetBool("是否为后台"))
            {
                BrowserList.data.Add((FBroSharpBrowser)browser);
                _form.UpdateStatus("浏览器已就绪");
            }
        }

        /// <summary>
        /// ⚠️ CRITICAL FOR SINGLE-WINDOW APPS: Popup control - Prevent new windows
        /// </summary>
        public override bool OnBeforePopup(
            IFBroSharpBrowser browser, 
            IFBroSharpFrame frame, 
            string target_url, 
            string target_frame_name,
            FBroSharpWindowOpenDisposition target_disposition, 
            bool user_gesture, 
            FBroSharpPopupfeatures popupFeatures, 
            ref FBroSharpWindowsInfo windowInfo,
            ref FBroSharpBrowserSetting settings,
            ref bool no_javascript_access, 
            IFBroSharpUseExtraData user_settings)
        {
            // Open in current window instead of new window
            frame.LoadURL(target_url);
            return true; // true = block popup, false = allow popup
        }

        /// <summary>
        /// ⚠️ REQUIRED: Address changed
        /// </summary>
        public override void OnAddressChange(IFBroSharpBrowser browser, IFBroSharpFrame frame, string url)
        {
            if (frame.IsMain())
            {
                _form.UpdateUrl(url);
            }
        }

        /// <summary>
        /// ⚠️ REQUIRED: Title changed
        /// </summary>
        public override void OnTitleChange(IFBroSharpBrowser browser, string title)
        {
            _form.UpdateTitle(title);
        }

        /// <summary>
        /// ⚠️ REQUIRED: Loading state changed
        /// </summary>
        public override void OnLoadingStateChange(IFBroSharpBrowser browser, bool isLoading, bool canGoBack, bool canGoForward)
        {
            _form.UpdateNavigationButtons(canGoBack, canGoForward);
            
            if (isLoading)
            {
                _form.UpdateStatus("正在加载...");
            }
        }

        /// <summary>
        /// ⚠️ REQUIRED: Page load started
        /// </summary>
        public override void OnLoadStart(IFBroSharpBrowser browser, IFBroSharpFrame frame, FBroSharpTransitionType transition_type)
        {
            if (frame.IsMain())
            {
                Console.WriteLine($"[BrowserEvent] 开始加载: {frame.GetURL()}");
            }
        }

        /// <summary>
        /// ⚠️ REQUIRED: Page load completed
        /// </summary>
        public override void OnLoadEnd(IFBroSharpBrowser browser, IFBroSharpFrame frame, int httpStatusCode)
        {
            if (frame.IsMain())
            {
                _form.UpdateStatus($"加载完成 (HTTP {httpStatusCode})");
                Console.WriteLine($"[BrowserEvent] 加载完成: {frame.GetURL()} (HTTP {httpStatusCode})");
            }
        }

        /// <summary>
        /// ⚠️ REQUIRED: Page load error (errorCode is int!)
        /// </summary>
        public override void OnLoadError(IFBroSharpBrowser browser, IFBroSharpFrame frame, 
            int errorCode, string errorText, string failedUrl)
        {
            if (frame.IsMain())
            {
                _form.UpdateStatus($"加载失败: {errorText}");
                Console.WriteLine($"[BrowserEvent] 加载错误: {errorText} (代码: {errorCode})");
            }
        }

        /// <summary>
        /// ⚠️ 接收来自 InitEvent 的 WebSocket 消息
        /// </summary>
        public override void ReceiveRenderProcessMessage(IFBroSharpBrowser browser, long processid, string name, byte[] message)
        {
            if (name == "websocket")
            {
                string data = Encoding.Default.GetString(message);
                Console.WriteLine($"[BrowserEvent] 收到 WebSocket 消息: {data}");
                
                // 在 UI 上显示 WebSocket 消息
                _form.AddWebSocketMessage(data);
            }
        }

        /// <summary>
        /// ⚠️ REQUIRED: Before browser close
        /// </summary>
        public override void OnBeforeClose(IFBroSharpBrowser browser)
        {
            // 从列表中移除浏览器
            for (int i = 0; i < BrowserList.data.Count; i++)
            {
                var temp_browser = BrowserList.data[i];
                if (temp_browser.IsSame(browser))
                    BrowserList.data.Remove(temp_browser);
            }
            
            Console.WriteLine("[BrowserEvent] 浏览器即将关闭");
        }

        /// <summary>
        /// ⚠️ REQUIRED: Can browser close
        /// </summary>
        public override bool DoClose(IFBroSharpBrowser browser)
        {
            return false; // false = allow close
        }
    }
}

